package com.lanou3g.ptp.sso.service.impl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.lanou3g.ptp.entity.*;
import com.lanou3g.ptp.sso.mapper.SsoMapper;
import com.lanou3g.ptp.sso.service.SsoService;
import com.lanou3g.ptp.student.service.StudentService;
import com.lanou3g.ptp.teacher.service.TeacherService;
import com.lanou3g.ptp.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class SsoServiceImpl implements SsoService {

    @Autowired
    private SsoMapper ssoMapper;

    @Reference(lazy = true)
    private StudentService studentService;

    @Reference
    private TeacherService teacherService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Value("${REDIS_TOKEN_KEY_PREFIX}")
    private String REDIS_TOKEN_KEY_PREFIX;

    @Value("${REDIS_TOKEN_KEY_EXPIRE}")
    private Long REDIS_TOKEN_KEY_EXPIRE;

    @Value("${ptp.password.salt}")
    private String PASSWORD_SALT;

    /**
     * 登录
     *
     * @param name
     * @param password
     * @return
     */
    @Override
    public String ssoUser(String name, String password) {
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        //通过 name  password 找到对应用户
        String pwd = null;
        try {
            pwd = MD5Utils.md5(password, PASSWORD_SALT);
        } catch (Exception e) {
            e.printStackTrace();
        }
        User user = ssoMapper.userByName(name, pwd);
        String userJson = null;
        if (user != null) {
            //通过user id 查询 个人详细信息
            Student student = studentService.studentById(user.getId());
            if (student != null) {
                student.setUser(user);
                student.setRole(4);
                userJson = JSON.toJSONString(student);
            } else {
                // 没有在学生表中找到学生
                //去查询老师表
                Teacher teacher = teacherService.findById(user.getId());
                teacher.setUser(user);
                //判定是不是学校老师  0为本校，1为校外
                if (teacher.getType().equals(1)) {
                    teacher.setRole(3);
                } else if (teacher.getMajorId() == null) {
                    teacher.setRole(2);
                } else {
                    teacher.setRole(1);
                }
                userJson = JSON.toJSONString(teacher);
            }
        } else {
            Admin admin = ssoMapper.findAdminByUnameAndPwd(name, pwd);
            if (admin != null) {
                admin.setRole(9);
                userJson = JSON.toJSONString(admin);
            }
        }
        if (userJson != null) {
            ////设置key值
            String key = REDIS_TOKEN_KEY_PREFIX + token;
            //用户信息存入redis
            redisTemplate.opsForValue().set(key, userJson, REDIS_TOKEN_KEY_EXPIRE, TimeUnit.MINUTES);
            return token;
        }
        return null;
    }

    //通过token查用户
    @Override
    public Object tokenUser(String token) {
        //通过key值 获取value
        String key = REDIS_TOKEN_KEY_PREFIX + token;
        String userJson = redisTemplate.opsForValue().get(key);
        Object user = null;
        if (userJson != null) {
            //序列化成map格式  查找key值中有没有 对应的值
            boolean isTeacher = JSON.parseObject(userJson).containsKey("type");
            if (isTeacher) {
                //有type 是老师
                //映射成老师
                user = JSON.parseObject(userJson, Teacher.class);
            } else {
                //没有type 是学生
                //映射成学生
                user = JSON.parseObject(userJson, Student.class);
            }
            redisTemplate.expire(key, REDIS_TOKEN_KEY_EXPIRE, TimeUnit.MINUTES);
        }
        return user;
    }

    @Override
    public Boolean changePass(UpdateUser updateUser, String tel, String No) {

        if (updateUser.getPassword().equals(updateUser.getPassword())) {
            return false;
        }

        if (tel.equals("")) {
            tel = No;
        }
        String pass = MD5Utils.md5(updateUser.getPassword(), PASSWORD_SALT);
        User user = ssoMapper.userByName(tel, pass);
        if (user != null) {
            String newPass = MD5Utils.md5(updateUser.getNewPassword(), PASSWORD_SALT);
            int degree = ssoMapper.changePass(tel, newPass);
            if (degree != 0) {
//                    redisTemplate.opsForValue().set();
                return true;
            } else {
                return false;
            }

        } else {
            return false;
        }


    }

    @Override
    public boolean logout(String token) {
        String key = REDIS_TOKEN_KEY_PREFIX + token;
        return redisTemplate.delete(key);
    }


}
